# 1. 准备工作
# 安装tuya-connector-python
# 安装命令：python -m pip install tuya-connector-python

# 2. 定义常量，务必替换成自己的
ACCESS_ID = 'n34pn3mjb5qr3n8up16k'
ACCESS_SEC = '6392bf3ed1034251a9b8b15a4138e9bb'
END_POINT = 'https://openapi.tuyacn.com'
PIR_ID = '6ca1efc38392f17a76rjuh'
ALERT_ID = '6ccf7254a3ec8a2c4dxrwo'

# 3. 连接到涂鸦
from tuya_connector import TuyaOpenAPI
tuyaAPI = TuyaOpenAPI(END_POINT, ACCESS_ID, ACCESS_SEC)
tuyaAPI.connect()

# 4. 获取PIR状态
def check_pir():
    res = tuyaAPI.get('/v1.0/iot-03/devices/{}/status'.format(PIR_ID))
    for kv in res["result"]:
        if kv['code'] == 'pir' and kv['value'] == 'pir':
            return True
    return False


# 5. 报警
def alert(level, time):
    commands = {
        "commands": [
            {
                "code": "alarm_time",
                "value": time
            },
            {
                "code": "alarm_setting",
                "value": level
            }
        ]
    }
    tuyaAPI.post("/v1.0/iot-03/devices/{}/commands".format(ALERT_ID), body=commands)

# 6. 主控程序
import time 
start_time = None
while True:
    if(check_pir()):
        now = time.time()
        if start_time == None:
            # 如果还没有记时，开始计时
            start_time = now 
        else:
            # 判断用了多久了
            used_time = now - start_time
            if used_time > 30:
                alert("2", 10)
                print('超过180秒，报警+闪灯10秒...')
            elif used_time > 20:
                alert("1", 5)
                print('超过120秒，报警3秒...')
            elif used_time > 10:
                alert("0", 5)
                print('超过60秒，闪灯3秒...')
            else:
                print('有人来了')
    else:
        # 人走了，清空计时
        start_time = None 
    time.sleep(5)
